#!/usr/bin/env python3

import os
import sys

class Stock(object):
    def __init__(self, fromfile=None):
        filepath = fromfile
        self.code = self._get_code_from_file_path(filepath)
        self.prices, self.volumes = self._get_prices_volumes_from_file(filepath)

    @staticmethod
    def _get_code_from_file_path(filepath):
        if not os.path.exists(filepath):
            raise Exception("file does not exist")
        basename = os.path.basename(filepath)
        code = basename.strip(".txSHZ#")
        return code

    @staticmethod
    def _get_prices_volumes_from_file(filepath):

        def get_data_lines_from_file(fpath):
            with open(fpath, 'r') as f:
                return '\n'.join(f.readlines())

        def get_prices_volumes(data_lines):
            """
            Return (prices, volumes)
            prices: a list of [pO, pH, pL, pC]
            volumes: a list of volume
            """
            prices = []
            volumes = []
            for line in data_lines.split('\n'):
                if line.strip() == "":
                    continue
                try:
                    date, pO, pH, pL, pC, v, vP = line.split()
                    prices.append([float(pO), float(pH), float(pL), float(pC)])
                    volumes.append(float(vP))
                except ValueError as e:
                    print("encounter value error in file '%s', line '%s'" % (filepath, line))
            return (prices, volumes)

        data_lines = get_data_lines_from_file(filepath)
        prices, volumes = get_prices_volumes(data_lines)
        return prices, volumes

    def getCode(self):
        return self.code
    
    def getPrices(self):
        return self.prices

    def getAverages(self, N):
        averages = []
        assert(N > 1)
        pCs = [price[3] for price in self.prices]
        for idx in range(0, len(pCs)):
            if idx < N-1:
                av = float(sum(pCs[:idx+1]) / (idx+1))
                averages.append(av)
            else:
                av = float(sum(pCs[idx-N+1:idx+1])/N)
                averages.append(av)
        return averages

if __name__ == '__main__':
    st = Stock(sys.argv[1])
    print(st.getCode())
    #print(st.getPrices())
    #print(st.getAverages(5))
